package com.yupi.project.util;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

import static com.yupi.project.constant.MQConstant.CodeHtml;

/**
 * @author <a href=""https://github.com/Fzs0>逢左使</a>
 * @create 2023/12/25 09:50
 * @Description:
 */
public class SendEmailUtil {

    /**
     * 发送邮件
     * @param toEmail
     * @return
     */
    public static String sendEmail(String toEmail) {
        // 随机生产的验证码
        String code = VerificationCodeGeneratorUtil.generateVerificationCode();
        // 发件人电子邮箱
        String from = "1520371000@qq.com";
        // 生成的授权码
        String password = "jxilfqnezerjjhbg";

        // 指定发送邮件的主机为 smtp.qq.com
        String host = "smtp.qq.com";  //QQ 邮件服务器

        // 获取系统属性
        Properties properties = System.getProperties();

        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);

        properties.put("mail.smtp.auth", "true");
        // 获取默认session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, password); //发件人邮件用户名、授权码
            }
        });

        // 设置debug模式便于调试:
        session.setDebug(true);

        try {
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);

            // Set From: 头部头字段
            message.setFrom(new InternetAddress(from));

            // Set To: 头部头字段
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));

            // Set Subject: 头部头字段
            message.setSubject("API接口平台验证码!", "UTF-8");
            String emailBody = CodeHtml.replace(":data=\"123456\"", ":data=\"" + code + "\"").replace("1EM456", code); //将发送页面的验证码改为后台生成的验证码
            // 设置消息体
            message.setText(emailBody, "UTF-8", "html");

            // 发送消息
            Transport.send(message);

            //发送完成后控制台打印输出
            System.out.println("Sent message successfully....");
        } catch (MessagingException mex) {
            mex.printStackTrace();
        }
        return code;
    }

}
